package controler;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import model.Constants;
import view.MainWindow;

public class CompleteLogger {

    private final SimpleFormatter formatter = new SimpleFormatter();
    private static Logger fileLogger = Logger.getAnonymousLogger();
    private final static CompleteLogger instance = new CompleteLogger();
    private MainWindow window;
    private FileHandler fh;

    public static CompleteLogger getLogger() {
        return CompleteLogger.instance;
    }

    private CompleteLogger() {
        super();
        try {
            this.fh = new FileHandler("log.log", false);
            fh.setFormatter(formatter);
            CompleteLogger.fileLogger.addHandler(fh);
            CompleteLogger.fileLogger.setUseParentHandlers(false);

        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void info(String log) {
        if (Constants.ACTIVATED_LOG_INFO) {
            System.out.println(CompleteLogger.getDateString() + " INFO: " + log);
            CompleteLogger.fileLogger.info(log);
        }
    }

    public void message(String log) {
        info(log);
        if (window != null) {
            window.setMessage(log);
            window.setAlarm(Constants.OK_MESSAGE);
        }
    }

    public void error(String log) {
        if (Constants.ACTIVATED_LOG_ERROR) {
            System.out.println(CompleteLogger.getDateString() + " ERROR: " + log);
            CompleteLogger.fileLogger.severe(log);
        }
        if (window != null) {
            window.setMessage(log);
            window.setAlarm(Constants.ERROR_MESSAGE);
        }
    }

    public void debug(String log) {
        if (Constants.ACTIVATED_LOG_DEBUG) {
            System.out.println(CompleteLogger.getDateString() + " DEBUG: " + log);
            CompleteLogger.fileLogger.config(log);
        }
    }

    public void setWindow(MainWindow window) {
        this.window = window;
    }

    static String getDateString() {
        Date date = new Date();
        DateFormat hourdateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return hourdateFormat.format(date);
    }
}
